#include <iostream>
#include <thread>
#include <chrono>
#include <event2/event.h>
#include <event2/thread.h>

void event_callback(evutil_socket_t fd, short events, void *arg) {
    static int count = 0;
    std::cout << "Main thread received event : " << count ++ << std::endl;
}

void worker_thread(void *arg) {
    for (int i = 0; i < 50; ++ i)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
        std::cout << "Worker thread triggering event: " << i << std::endl;
        event_active((struct event *)arg, EV_READ, 0);
    }
    std::this_thread::sleep_for(std::chrono::seconds(1));
    event_del((struct event *)arg);
}

int main()
{
    #ifdef _WIN32
    WSADATA wsa_data;
    WSAStartup(0x0202, &wsa_data);
    evthread_use_windows_threads();
    #else
    evthread_use_pthreads();
    #endif

    struct event_base* base = event_base_new();
    if (!base) {
        std::cerr << "Could not initialize libevent!" << std::endl;
        return 1;
    }

    struct event* ev = event_new(base, -1, EV_READ | EV_PERSIST, event_callback, nullptr);
    if (!ev) {
        std::cerr << "Could not create event!" << std::endl;
        return 1;
    }
    event_add(ev, nullptr);

    std::thread worker(worker_thread, ev);

    event_base_dispatch(base);

    worker.join();
    event_free(ev);
    event_base_free(base);

    #ifdef _WIN32
    WSACleanup();
    #endif

    return 0;
}
